<?php

if (!defined('IN_XLP')) {
    exit('Access Denied');
}

/**
 * Description of menuAction
 * 商品管理
 * @author skyinter
 */
class goodsAction extends commonAction {

    function __construct() {
        parent::__construct();
        parent::_checkLogin();
    }

    /**
     * 商品列表
     */
    public function index() {

        $page = $this->_get('page') ? $this->_get('page') : '1';
        $keyword = $this->_get('keyword') ? $this->_get('keyword') : '';

        $where = '`is_del` = 0';
        if ($_GET) {
            $keyword = $this->_get('keyword') ? $this->_get('keyword') : '';
            $where .= " and `goods_name` like '%" . $keyword . "%'";
        }
        $goods_list = D('goods')->get_list($page, $where);
        $total = D('goods')->getTotal();

        $cate_list = D('goodsCategory')->get_list('`id`,`name`');
        foreach ($goods_list as $k => $v) {
            if ($goods_list[$k]['cid']) {
                $goods_list[$k]['cid'] = $cate_list[$v['cid']]['name'];
            }
            //判断上下架状态
            if ($v['state'] == 1) {
                $goods_list[$k]['state'] = '<b style="color:green">上架</b>';
            } else if ($v['state'] == 2) {
                $goods_list[$k]['state'] = '<b style="color:red">下架</b>';
            }
        }

        $this->assign('list', $goods_list);
        $this->assign('page', $page);
        $this->assign('total', $total);
        $this->assign('keyword', $keyword);
        $this->display();
    }



    /**
     * 预约咨询
     */
    public function lists() {

        $page = $this->_get('page') ? $this->_get('page') : '1';
        // $keyword = $this->_get('keyword') ? $this->_get('keyword') : '';

        // $where = '`is_del` = 0';
        // if ($_GET) {
        //     $keyword = $this->_get('keyword') ? $this->_get('keyword') : '';
        //     $where .= " and `goods_name` like '%" . $keyword . "%'";
        // }
        $where = '1=1';
        $order_list = D('order')->get_list($page, $where);
        $total = D('order')->getTotal();
        $cate_list = D('goodsCategory')->get_list('`id`,`name`');
        foreach ($order_list as $k => &$v) {
            if ($order_list[$k]['user_id']) {
                $order_list[$k]['user_id'] = $cate_list[$v['user_id']]['name'];
            }
            $dot = D('Article')->field("title,author,url")->where(array('id' => $v['lender_id']))->find();
            $v['dot'] = $dot;
        }

        $this->assign('list', $order_list);
        $this->assign('page', $page);
        $this->assign('total', $total);
        // $this->assign('keyword', $keyword);
        $this->display();
    }

    /**
     * 添加商品
     */
    public function add() {
        //执行添加商品操作
        if ($_POST) {
            $tablefields = M('goods')->getTableFields();

            $data = array();
            foreach ($tablefields['fields'] as $key => $value) {
                if (!isset($_POST[$key]))
                    continue;
                $data[$key] = trim($this->_post($key));
            }

            $data['create_time'] = time();
            $result = D('goods')->add($data);
            if ($result !== false) {
                $this->JsonReturn('添加产品成功', null, 1);
            } else {
                $this->JsonReturn('添加产品失败', null, 0);
            }
            exit;
        }

        //商品分类
        $goods_cate = D('goodsCategory')->get_option();
        $this->assign('goods_cate', $goods_cate);

        $this->display();
    }

    /**
     * 商品编辑
     */
    public function edit() {

        if ($_POST) {
            $id = $this->_postid('id');
            $tablefields = M('goods')->getTableFields();

            $data = array();
            foreach ($tablefields['fields'] as $key => $value) {
                if (!isset($_POST[$key]))
                    continue;
                $data[$key] = trim($this->_post($key));
            }
            $result = D('goods')->modify($id, $data);
            if ($result !== false) {
                $this->JsonReturn('编辑产品成功', null, 1);
            } else {
                $this->JsonReturn('编辑产品失败', null, 0);
            }
            exit;
        }

        //商品信息
        $id = $this->_get('id');
        $info = D('goods')->info($id);
        $this->assign('info', $info);

        //商品分类
        $goods_cate = D('goodsCategory')->get_option($info['cid']);
        $this->assign('goods_cate', $goods_cate);
        $this->display();
    }

    /**
     * 商品分类
     */
    public function cate() {
        $page = $this->_get('page') ? $this->_get('page') : '1';
        $keyword = $this->_get('keyword') ? $this->_get('keyword') : '';
        $list = D('goodsCategory')->get_list();
        $total = D('goodsCategory')->getTotal();

        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('keyword', $keyword);
        $this->display();
    }


    public function cateAdd() {
        if ($_POST) {
            $data['name'] = $this->_post('name');
            $data['sort'] = $this->_post('sort');
            $data['is_show'] = $this->_post('is_show');
            $data['sub_title'] = $this->_post('sub_title');
            $data['brief'] = $this->_post('brief');
            $data['content'] = $this->_post('content');
            $data['back_img'] = $this->_post('back_img');
            $data['trade_time'] = $this->_post('trade_time');
            $result = D('goodsCategory')->add($data);
            if ($result > 0) {
                $this->JsonReturn('添加分类成功', null, 1);
            } else {
                $this->JsonReturn('添加分类失败', null, 0);
            }
            exit;
        }
        $this->display();
    }


    public function cateEdit() {
        if ($_POST) {
            $id = $this->_post('id');
            $data['name'] = $this->_post('name');
            $data['sort'] = $this->_post('sort');
            $data['is_show'] = $this->_post('is_show');
            $data['sub_title'] = $this->_post('sub_title');
            $data['brief'] = $this->_post('brief');
            $data['content'] = $this->_post('content');
            $data['back_img'] = $this->_post('back_img');
            $data['trade_time'] = $this->_post('trade_time');
            $result = D('goodsCategory')->modify($id , $data);
            if ($result > 0) {
                $this->JsonReturn('编辑分类成功', null, 1);
            } else {
                $this->JsonReturn('编辑分类失败', null, 0);
            }
            exit;
        }
        $cid = $this->_getid('cid' , 0);
        if(!isHave($cid)) {
            $this->error('参数丢失');
        }
        $cate = D('goodsCategory')->where(array('id' => $cid))->find();
        $this->assign('cate' , $cate);
        $this->display();
    }


    /**
     * 商品规格
     */
    public function spec() {
        //规格
        $spec = M('spec')->field('`id`,`spec_name`')->order('`sort`')->findAll();
        //规格值
        $spec_value = M('spec_value')->field('`id`,`spec_id`,`spec_value`,`spec_tips`')->findAll();

        if (count($spec)) {
            foreach ($spec as $k => $v) {
                $spec[$k]['spec_value'] = array();
                if (!count($spec_value))
                    break;
                foreach ($spec_value as $key => $value) {
                    if ($value['spec_id'] == $v['id']) {
                        $spec[$k]['spec_value'][] = $value;
                        unset($spec_value[$key]);
                    }
                }
            }
        }
        // z($spec);
        $this->assign('spec', $spec);
        $this->display();
    }

    /*
     * 添加商品规格
     */

    public function specadd() {

        if (isset($_POST['spec_name'])) {
            $spec_name = $this->_post('spec_name');
            $spec_sort = $this->_post('spec_sort');

            //检查规格是否已经存在
            $is_exist = M('spec')->where(array('spec_name' => $spec_name))->find();
            if ($is_exist)
                sendJson(array('err' => 1, 'msg' => '该规格已经存在'));

            //插入规格
            $spec_id = M('spec')->insert(array('spec_name' => $spec_name, 'sort' => $spec_sort));

            if ($spec_id) {
                $spec_value = $this->_post('spec_value');
                $spec_num = count($spec_value);
                //是否有规格值
                if ($spec_num && $spec_value[0]) {
                    //规格备注
                    $spec_tips = $this->_post('spec_tips');

                    $data = array();
                    for ($i = 0; $i < $spec_num; $i++) {
                        $data[] = array(
                            'spec_id' => $spec_id,
                            'spec_name' => $spec_name,
                            'spec_value' => $spec_value[$i],
                            'spec_tips' => $spec_tips[$i],
                        );
                    }
                    //插入规格值
                    $insert_num = M('spec_value')->insertAll($data);

                    if ($insert_num != $spec_num) {
                        sendJson(array('err' => 1, 'msg' => '部分规格值添加失败'));
                    } else {
                        sendJson(array('err' => 0, 'msg' => '规格和规格值添加成功'));
                    }
                }

                sendJson(array('err' => 0, 'msg' => '规格添加成功'));
            } else {
                sendJson(array('err' => 1, 'msg' => '规格添加失败'));
            }
        }

        $this->display();
    }

    /*
     * 添加商品规格值
     */

    public function spec_value_add() {
        $spec_value_id = $this->_post('spec_value_id');
        $spec_id = $this->_post('spec_id');
        $spec_name = $this->_post('spec_name');
        $spec_value = $this->_post('spec_value');
        $spec_tips = $this->_post('spec_tips');

        if (trim($spec_value) == '') {
            sendJson(array('err' => 1, 'msg' => '规格值不能为空'));
        }

        //查找规格是否存在
        $is_exist = M('spec_value')->where(
                        array(
                            'spec_id' => $spec_id,
                            'spec_value' => $spec_value,
                            'spec_tips' => $spec_tips)
                )->find();

        if ($is_exist)
            sendJson(array('err' => 1, 'msg' => '该规格已经存在'));

        //添加OR更新
        if ($spec_value_id) {
            M('spec_value')->update(array('spec_value' => $spec_value, 'spec_tips' => $spec_tips), array('id' => $spec_value_id));
            sendJson(array('err' => 0, 'msg' => '规格更新成功'));
        } else {
            M('spec_value')->insert(
                    array('spec_id' => $spec_id, 'spec_name' => $spec_name, 'spec_value' => $spec_value, 'spec_tips' => $spec_tips)
            );
            sendJson(array('err' => 0, 'msg' => '规格添加成功'));
        }
    }

    /**
     * 商品分析
     */
    public function stat() {
        $this->display();
    }

    /**
     * 属性管理
     */
    public function addr() {
        $this->display();
    }

    /**
     * 商品评论
     */
    public function comment() {
        $this->display();
    }

    /**
     * 删除图片文件
     */
    public function removefile() {
        $url = $this->_post('url');
        if(!$url) {
            $this->JsonReturn('参数丢失', null, 0);
        }
        if(@unlink($url)){
            $this->JsonReturn('删除文件成功', null, 1);
        }else{
            $this->JsonReturn('删除文件失败', null, 0);
        }
    }


    public function ajax() {
        $id = $this->_get('id') ? $this->_get('id') : null;
        $type = $this->_get('type') ? $this->_get('type') : null;

        switch ($type) {
            case 'down': //商品下架
                $data = array('state' => 2);
                $stat = D('goods')->modify($id, $data);
                break;
            case 'del': //商品删除
                $stat = D('goods')->where(array('id'=>$id))->delete();
                break;
            case 'up': //商品上架
                $data = array('state' => 1);
                $stat = D('goods')->modify($id, $data);
                break;
            case 'cateSave': //商品类别名称更改
                $data = array('name' => $this->_get('name'));
                $stat = D('goodsCategory')->modify($id, $data);
                break;
            case 'cateDel': //分类
                $result = D('goods')->where(array('cid'=>$id))->find();
                if($result) {
                    $this->JsonReturn('该分类下有产品，无法删除', null , 0);
                }
                $stat = D('goodsCategory')->where(array('id'=>$id))->delete();
                break;
            case 'cdel':
                $stat = D('order')->where(array('id' => $id))->delete();
                break;    
            default:
                $stat = 0;
                break;
        }

        if ($stat > 0) {
            $info = '请求成功';
            $this->JsonReturn($info, null, 1);
        } else {
            $info = '请求失败';
            $this->JsonReturn($info, null, 0);
        }
    }

    //正常上传
    function upload() {
        if (parent::_checkLogin(true)) {
            load('upload');
            $myUpload = new Myupload();
            $upload = $myUpload->upload('goods/u' . admin::$adminInfo['aid']);
            $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
            if ($upload) {
                $upload = $upload[0];
                if (!$upload) {
                    echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => $myUpload->getErrorMsg()));
                } else {
                    echo json_encode(array('url' => $upload['savepath'], 'fileType' => $upload['type'], 'original' => $upload['realname'], 'state' => 'SUCCESS'));
                }
            }
        } else {
            echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => '上传失败'));
        }
    }

    /*
     * 导出商品货号对应表
     */

    public function export_goods_sn() {
        $data = M('goods')
                ->field('`goods_name`,`goods_sn`')
                ->where('`is_del`<>1')
                ->findAll();

        load('csv');
        $csv = new csv();
        $csv->write(array(), $data, "商品货号表" . date('Y-m-d'));
    }

}
